package com.nxy.cpfsfe.busi.unfyag;

import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.nxy.cpfsfe.enumtype.MsgCdOrTpEnum;
import com.nxy.cpfsfe.enumtype.RespCd;
import com.nxy.cpfsfe.enumtype.RpcOutputInfoEnum;
import com.nxy.cpfsfe.enumtype.SysEcodeEnum;
import com.nxy.cpfsfe.service.CpfsService;
import com.nxy.cpfsfe.service.factory.ForwardServer;
import com.nxy.cpfsfe.service.factory.ForwordFactory;
import com.nxy.cpfsfe.util.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Description转发类同步流程
 * Created by lcq on 2019/12/25.
 */
public class ForwardSrvBean implements CpfsService {
    private final static Logger LOGGER = LoggerFactory.getLogger(ForwardSrvBean.class);

    @Override
    public void doService() {
        LOGGER.debug("---------转发类同步流程业务开始---------");
        Map<String,String> map = null;
        String rpsMsg ="";
        String tpId = DtaInfo.getInstance().getTpId();
        // 获取输入
        CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口
        try {
            String MsgTp = (String)EPOper.get(tpId, "ReqBean[0].head[0].MsgTp");
            String bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):""; // 业务报文
            LOGGER.info("CPFS业务报文编号[{}],CPFS业务报文：[{}]",MsgTp,bizMsg);
            //生成业务map
            map = XmlUtil.xml2Map(bizMsg);
            //2、组装esb报文并发送报文
            ForwardServer server = ForwordFactory.getForwardService(MsgTp);
            if(server != null){
                //组装报文
                String esbXml =server.buildEsbXml(map);
                //发送报文并获得响应报文数据信息
                String responseMsg = handleCBS(map,esbXml);
                //解析esb响应结果
                rpsMsg  = server.handleRpsMsg(map,responseMsg);
            }else{
                LOGGER.warn("[{}]业务未配置",MsgTp);
                map.put("msg", MsgTp+"业务未配置");
                map.put("resultCode",RespCd.NCPO3999);
            }
            //主动发往nginx或者业务系统
        }catch (BaseException e) {
            LOGGER.error("转发类同步流程处理失败,错误码[{}],错误原因[{}]",e.getErrorCode(),e.getErrorDesc());
            LOGGER.error("错误信息栈",e);
            map.put("msg", e.getErrorDesc());
            map.put("resultCode",e.getErrorCode());
        }catch (Throwable e) {
            LOGGER.error("转发类同步流程处理失败",e);
            map.put("msg", "转发类同步流程处理失败");
            map.put("resultCode",RespCd.NCPO3999);
        }
        ResponseUtil.responseSend(rpsMsg,map);
        LOGGER.debug("---------转发类业务同步响应成功---------");
    }
    /**
     * 处理cbs响应报文
     * @param rpsMsg
     * @param map
     */
    private void handleRpsMsg(String rpsMsg, Map<String, String> map){
        //判断回执报文是否为空
        if(StringUtils.isNotBlank(rpsMsg)){
            Map<String,String> rpsmap = XmlUtil.xml2Map(rpsMsg);
            String  retCd = StringUtil.trimObject(rpsmap.get("/transaction/header/status/retCd"));
            //返回码前两位为00代表成功
            if(retCd.startsWith("00")&&retCd.length() ==6){
                return ;
            }else{
                map.put("msg", StringUtil.trimObject(rpsmap.get("/transaction/header/status/desc")));
                map.put("resultCode",retCd);
            }
        }else{
            LOGGER.error("esb回执报文为空，请联系");
            map.put("msg", "esb回执报文为空，请联系");
            map.put("resultCode",RespCd.NCPO0005);
        }
    }

    /**
     * cbs报文组装并调用网关处理
     * @param map
     * @return
     */
    private String handleCBS(Map<String, String> map,String cbsXml) {
        String tpId = DtaInfo.getInstance().getTpId();
        String rspMsg="";
        try{
            LOGGER.info("CBS报文[{}]",cbsXml);
            EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", SysEcodeEnum.PESB.getCode());
            EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", MsgCdOrTpEnum.CBS_3300.getCode());
            EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg", cbsXml);
            rspMsg = RpcCommUtil.getInstance().rpcFeToGWRetMsg(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());
        }catch(Exception e){
            LOGGER.error("调用网关转发报文服务失败",e);
            throw new BaseException(RespCd.NCPO6047,e,"调用网关服务异常");
        }
        return rspMsg;
    }
}
